package space.sakana.edusysback.service;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import space.sakana.edusysback.entity.Admin;
import space.sakana.edusysback.entity.Subject;
import space.sakana.edusysback.mapper.AdminMapper;
import space.sakana.edusysback.mapper.SubjectMapper;
import space.sakana.edusysback.result.DataResult;
import space.sakana.edusysback.result.Result;
import space.sakana.edusysback.util.CookieUtil;

@Service
public class SubjectService {

    private SubjectMapper subjectMapper;
    private AdminMapper adminMapper;

    @Autowired
    public void autowiredMapper(SubjectMapper subjectMapper, AdminMapper adminMapper){
        this.subjectMapper = subjectMapper;
        this.adminMapper = adminMapper;
    }

    public Result getAllSubject(HttpServletRequest request, HttpServletResponse response) {
        Admin admin = adminMapper.selectAdminByToken(CookieUtil.getCookieValueByKey("token", request));
        if (admin==null){
            return Result.failResult;
        }

        return new DataResult(JSON.toJSONString(subjectMapper.selectAllSubject()));
    }

    public Result addSubject(String data, HttpServletRequest request, HttpServletResponse response) {
        Admin admin = adminMapper.selectAdminByToken(CookieUtil.getCookieValueByKey("token", request));
        if (admin==null){
            return Result.failResult;
        }

        return new Result(subjectMapper.insertSubject(JSON.parseObject(data, Subject.class)));
    }

    public Result updateSubject(String data, HttpServletRequest request, HttpServletResponse response) {
        Admin admin = adminMapper.selectAdminByToken(CookieUtil.getCookieValueByKey("token", request));
        if (admin==null){
            return Result.failResult;
        }

        return new Result(subjectMapper.updateSubject(JSON.parseObject(data, Subject.class)));
    }

    public Result getSubject(int sid, HttpServletRequest request, HttpServletResponse response) {
        Admin admin = adminMapper.selectAdminByToken(CookieUtil.getCookieValueByKey("token", request));
        if (admin==null){
            return Result.failResult;
        }

        return new DataResult(JSON.toJSONString(subjectMapper.selectSubjectById(sid)));
    }

    public Result deleteSubject(int sid, HttpServletRequest request, HttpServletResponse response) {
        Admin admin = adminMapper.selectAdminByToken(CookieUtil.getCookieValueByKey("token", request));
        if (admin==null){
            return Result.failResult;
        }

        return new Result(subjectMapper.deleteSubjectById(sid));
    }
}
